/* contact_msg的数据结构(PostgreSQL)
CREATE TABLE contact_msg (
 id SERIAL PRIMARY KEY,
 firstname TEXT NOT NULL,
 lastname TEXT NOT NULL,
 budget TEXT NOT NULL,
 email TEXT NOT NULL,
 message TEXT NOT NULL,
 created_at TIMESTAMP DEFAULT NOW()
);
*/
const Router = require("@koa/router");
const { Pool } = require("pg");
const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
const router = new Router({ prefix: "/contact_msg" });

// 配置数据库连接池
const pool = new Pool({
  user: process.env.DB_USER,
  host: process.env.DB_HOST,
  database: process.env.DB_DATABASE,
  password: process.env.DB_PASSWORD,
  port: process.env.DB_PORT,
});

// 频率限制存储 - 使用内存存储，生产环境建议使用Redis
const rateLimitStore = new Map();

// 频率限制中间件 - 限制每个IP每分钟最多2次请求
const rateLimitMiddleware = async (ctx, next) => {
  const clientIP = ctx.request.ip || ctx.request.ips[0] || 'unknown';
  const now = Date.now();
  const windowMs = 60 * 1000; // 1分钟
  const maxRequests = 2; // 最大请求次数
  
  // 清理过期的记录
  for (const [ip, data] of rateLimitStore.entries()) {
    if (now - data.timestamp > windowMs) {
      rateLimitStore.delete(ip);
    }
  }
  
  const clientData = rateLimitStore.get(clientIP);
  
  if (!clientData) {
    // 第一次请求
    rateLimitStore.set(clientIP, {
      count: 1,
      timestamp: now
    });
    return next();
  }
  
  if (now - clientData.timestamp > windowMs) {
    // 时间窗口已过，重置计数
    rateLimitStore.set(clientIP, {
      count: 1,
      timestamp: now
    });
    return next();
  }
  
  if (clientData.count >= maxRequests) {
    // 超过限制
    ctx.status = 429;
    ctx.body = {
      success: false,
      message: '请求过于频繁，请稍后再试'
    };
    return;
  }
  
  // 增加计数
  clientData.count++;
  rateLimitStore.set(clientIP, clientData);
  
  return next();
};

// 新增联系消息接口
router.post("/", rateLimitMiddleware, async (ctx) => {
  try {
    const { firstname, lastname, budget, email, message } = ctx.request.body;
    
    // 验证必填字段
    if (!firstname || !lastname || !budget || !email || !message) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '所有字段都是必填的'
      };
      return;
    }
    
    // 验证邮箱格式
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '邮箱格式不正确'
      };
      return;
    }
    
    // 插入数据库
    const query = `
      INSERT INTO contact_msg (firstname, lastname, budget, email, message)
      VALUES ($1, $2, $3, $4, $5)
      RETURNING id, created_at
    `;
    
    const values = [firstname, lastname, budget, email, message];
    const result = await pool.query(query, values);
    
    ctx.status = 201;
    ctx.body = {
      success: true,
      message: '消息提交成功',
      data: {
        id: result.rows[0].id,
        created_at: result.rows[0].created_at
      }
    };
    
  } catch (error) {
    console.error('新增联系消息错误:', error);
    ctx.status = 500;
    ctx.body = {
      success: false,
      message: '服务器内部错误'
    };
  }
});

// 导出路由
module.exports = router;